package org.jeecg.modules.demo3.fly.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.SocketProperties;
import org.jeecg.modules.demo3.fly.TCP.ServerConfig;
import org.jeecg.modules.demo3.fly.entity.tcp.Clents;
import org.jeecg.modules.demo3.fly.entity.tcp.SocketClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author wjn
 * @version V1.0
 * @date 2021/2/24 14:16
 * @Copyright © 2021/2/24 深圳卓翼航空无人机有限公司
 */
@RestController
@RequestMapping("/fly/axhkTCP")
@Slf4j
public class AxhkTCPController {
    /*  @Autowired
        private SocketProperties properties;*/


    @GetMapping("tcp")
    public void getTCP() {
        ServerSocket serverSocket;
        try {
            //创建一个客户端的集合 装去客户端登录的socket
            List<Clents> sockets = new ArrayList<Clents>();
            List<Clents> synchronizedList = Collections.synchronizedList(sockets);
            serverSocket = new ServerSocket(2222);//开启服务的端口，需和客户端一致
            System.out.println("服务端已经启动，等待客户端连接");
            //通过调用Executors类的静态方法，创建一个ExecutorService实例
            ExecutorService service = Executors.newCachedThreadPool();
            while (true) {
                System.out.println("创建socket 循环");
                //实时监测
                Socket socket = serverSocket.accept(); //对客户端的访问进行监听
                System.out.println(socket);
                System.out.println("客户端的IP：" + socket.getInetAddress().getHostAddress());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String inTime = simpleDateFormat.format(new Date());
                System.out.println("TCP进入时间=" + inTime);
                if (null != socket) {
                    System.out.println("socket不为空");
                    //创建 客户端对象
                    Clents clents = new Clents(socket);
                    //集合添加
                    synchronizedList.add(clents);
                    service.execute(new ServerConfig(clents, synchronizedList));//开启输入和输出的多线程
                }
            }
        } catch (IOException exception) {
            exception.printStackTrace();
            System.out.println("创建socket异常");
        }
    }




}
